package thread.optimisticlock;

public class LockObj {

	/**
	 * 版本
	 */
	private volatile int version = 0;
	
	public int getVersion() {
		return this.version;
	}
	
	/**
	 * 操作对象
	 */
	private volatile Bean bean;
	
	public Bean getBean() {
		return bean;
	}

	public void setBean(Bean bean) {
		this.bean = bean;
	}

	public boolean changeBean(int currentVersion, Bean bean){
		if(currentVersion != this.version || bean.getState() != this.bean.getState()){
			return false;
		}
		this.addVersion();
		this.bean.addState();
		if(this.version != currentVersion+1){
			downVersion();
			this.bean.downState();
			return false;
		}
		return true;
	}
	
	private synchronized void addVersion() {
		++this.version;
	}
	
	private synchronized void downVersion() {
		--this.version;
	}
}
